<<<<<<< HEAD
<!-- 确保在<head>中加载了jQuery -->

// 确认模态框控制
const confirmModal = document.getElementById('confirm-modal');
const cancelConfirm = document.getElementById('cancel-confirm');
const confirmAction = document.getElementById('confirm-action');
const confirmTitle = document.getElementById('confirm-title');
const confirmMessage = document.getElementById('confirm-message');

// 当前操作的房屋ID
let currentHouseId = '';
// 当前操作类型 (上架/下架)
let currentAction = '';
// 打开确认模态框
function openConfirmModal(id, action) {
    debugger
    currentHouseId = id;
    currentAction = action;

    if (action === '下架') {
        confirmTitle.textContent = '确认下架';
        confirmMessage.textContent = '您确定要将此房屋下架吗？下架后用户将无法看到该房屋。';
        confirmAction.classList.remove('btn-success');
        confirmAction.classList.add('btn-danger');
        confirmAction.innerHTML = '<i class="fa fa-ban"></i><span>确认下架</span>';
    } else if (action === '上架') {
        confirmTitle.textContent = '确认上架';
        confirmMessage.textContent = '您确定要将此房屋上架吗？上架后用户将可以看到并预订该房屋。';
        confirmAction.classList.remove('btn-danger');
        confirmAction.classList.add('btn-success');
        confirmAction.innerHTML = '<i class="fa fa-check-circle"></i><span>确认上架</span>';
    } else if (action === 'delete') {
        confirmTitle.textContent = '确认删除';
        confirmMessage.textContent = '您确定要删除此房屋吗？删除后数据将无法恢复。';
        confirmAction.classList.remove('btn-success');
        confirmAction.classList.add('btn-danger');
        confirmAction.innerHTML = '<i class="fa fa-trash"></i><span>确认删除</span>';
    }

    confirmModal.classList.remove('hidden');
    confirmModal.classList.add('flex');
    document.body.style.overflow = 'hidden';
}
// 关闭确认模态框
function closeConfirmModal() {
    confirmModal.classList.add('hidden');
    confirmModal.classList.remove('flex');
    document.body.style.overflow = '';
}

cancelConfirm.addEventListener('click', closeConfirmModal);

// 点击确认模态框外部关闭
confirmModal.addEventListener('click', (e) => {
    if (e.target === confirmModal) {
        closeConfirmModal();
    }
});

// 关闭确认模态框
function closeConfirmModal() {
    confirmModal.classList.add('hidden');
    confirmModal.classList.remove('flex');
    document.body.style.overflow = '';
}
// 通知提示框
const toast = document.getElementById('toast');
const toastIcon = document.getElementById('toast-icon');
const toastTitle = document.getElementById('toast-title');
const toastMessage = document.getElementById('toast-message');
const closeToast = document.getElementById('close-toast');

function showToast(type, title, message) {
    // 设置提示类型
    if (type === 'success') {
        toastIcon.className = 'text-success mt-0.5';
        toastIcon.innerHTML = '<i class="fa fa-check-circle text-xl"></i>';
    } else if (type === 'error') {
        toastIcon.className = 'text-danger mt-0.5';
        toastIcon.innerHTML = '<i class="fa fa-times-circle text-xl"></i>';
    } else if (type === 'warning') {
        toastIcon.className = 'text-warning mt-0.5';
        toastIcon.innerHTML = '<i class="fa fa-exclamation-triangle text-xl"></i>';
    }

    // 设置内容
    toastTitle.textContent = title;
    toastMessage.textContent = message;

    // 显示提示
    toast.classList.remove('translate-x-full');

    // 3秒后自动关闭
    setTimeout(() => {
        hideToast();
    }, 3000);
}


function hideToast() {
    toast.classList.add('translate-x-full');
}

const houseModal = document.getElementById('house-modal');
const closeModal = document.getElementById('close-modal');
const cancelModal = document.getElementById('cancel-modal');
const modalTitle = document.getElementById('modal-title');

// 关闭模态框
function closeHouseModal() {
    houseModal.classList.add('hidden');
    houseModal.classList.remove('flex');
    document.body.style.overflow = '';
}

closeModal.addEventListener('click', closeHouseModal);
cancelModal.addEventListener('click', closeHouseModal);
function getHouseDataById(id) {
    $.ajax({
        url: baseUrl + "/admin/info/"+id,
        type: "get",

        success: function (res) {
            console.log(res)
            if (res.code == "0") {
                viewHouseDetail(res.data)
            } else {
                console.log("没有成功查询房源");
            }
        },
        error: function (res) {

            console.log(res)
        }
    });
}

// 查看房屋详情
function viewHouseDetail(houseData) {

    if (houseData) {
        let imgUrl=baseUrl+houseData.pic;
        // 创建详情模态框内容
        const detailContent = `
      <div class="p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <img src="${imgUrl}" alt="${houseData.name}" class="w-full h-64 object-cover rounded-lg">
          </div>
          <div>
            <h3 class="text-xl font-bold mb-2">${houseData.name}</h3>
            <p class="text-gray-600 mb-4">${houseData.place}</p>
            <div class="grid grid-cols-2 gap-4 mb-4">
              <div>
                <p class="text-sm text-gray-500">租金</p>
                <p class="font-medium">${houseData.price}元/月</p>
              </div>
              <div>
                <p class="text-sm text-gray-500">面积</p>
                <p class="font-medium">${houseData.area}㎡</p>
              </div>
              <div>
                <p class="text-sm text-gray-500">户型</p>
                <p class="font-medium">${houseData.type}</p>
              </div>
              <div>
                <p class="text-sm text-gray-500">状态</p>
                <p class="font-medium">${houseData.state}</p>
              </div>
            </div>
            <div class="mb-4">
              <p class="text-sm text-gray-500 mb-1">房屋描述</p>
              <p class="text-gray-700">${houseData.decorateSituation}</p>
            </div>
          </div>
        </div>
      </div>
    `;

        // 创建并显示详情模态框
        const detailModal = document.createElement('div');
        detailModal.id = 'detail-modal';
        detailModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4';
        detailModal.innerHTML = `
      <div class="card w-full max-w-4xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-bold">房屋详情</h3>
          <button class="close-detail-modal text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        ${detailContent}
        <div class="p-6 border-t border-gray-200 flex items-center justify-end">
          <button class="close-detail-modal btn btn-primary">关闭</button>
        </div>
      </div>
    `;

        document.body.appendChild(detailModal);
        document.body.style.overflow = 'hidden';

        // 关闭详情模态框事件
        detailModal.querySelectorAll('.close-detail-modal').forEach(btn => {
            btn.addEventListener('click', () => {
                detailModal.remove();
                document.body.style.overflow = '';
            });
        });
    }
}

    $(document).ready(function(){
        let houseId="";
        let action="";
        $(document).on("click", "#add-house-btn", function(){
            modalTitle.textContent = '新增房屋';
            houseModal.classList.remove('hidden');
            houseModal.classList.add('flex');
            document.body.style.overflow = 'hidden';
            handleState="添加"
        });

        $(document).on("click", ".detail-btn", function(){
            getHouseDataById($(this).data("id"))
        });
        $(document).on("click", ".delete-btn", function(){
            action="delete";
            openConfirmModal($(this).data("id"), 'delete');
        });
        const imageUpload = document.getElementById('image-upload');
        const imagePreview = document.getElementById('image-preview');
        $(document).on("change", "#image-upload", function(e){
            debugger
            if (e.target.files.length > 0) {
                imagePreview.classList.remove('hidden');
                // 实际项目中应该根据上传的文件显示预览
                // 这里只是简单显示示例图片
                // 获取文件输入元素
                // const fileInput = $(imageUpload); // 假设你的文件输入框id为fileInput

// 创建FormData对象并添加文件
                const formData = new FormData();
                formData.append('file', imageUpload.files[0]); // 'file'为后端接收的参数名
                //formData.append('extraParam', 'value'); // 可添加其他参数

                $.ajax({
                    url: baseUrl + "file/upload",
                    type: "POST",
                    data: formData,

                    // 必须配置项
                    contentType: false, // 必须false才会自动带上正确的Content-Type
                    processData: false, // 必须false才会避免jQuery将FormData转为字符串

                    // 可选：上传进度提示
                    xhr: function() {
                        const xhr = new XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                const percent = Math.round((e.loaded / e.total) * 100);
                                console.log('上传进度:', percent + '%');
                                // 可在此处更新进度条UI
                            }
                        }, false);
                        return xhr;
                    },

                    success: function(res) {
                        console.log(res)
                        if (res.code == "0") {
                            console.log('上传成功:', res);
                            imageUrl=res.file;
                            // 处理成功逻辑，例如显示预览图
                            $('#backImg').attr('src',baseUrl+ res.file+"?time="+new Date().getTime());
                        } else {
                            console.error('上传失败:');
                            // alert('上传失败: ' + res.message);
                        }
                    },

                    error: function(xhr, status, error) {
                        console.error('请求异常:', status, error);
                        alert('上传请求失败，请检查网络连接');
                    }
                });
            }
        });
        // 如果是动态按钮
        $(document).on("click", ".上架-btn", function(){
            // alert($(this).data("id")); // 可以获取data-id属性
            houseId=$(this).data("id")
            action="上架"
            openConfirmModal(houseId, "上架")
        });
        $(document).on("click", ".delete-btn", function(){
            houseId=$(this).data("id")
            action="delete"
            openConfirmModal(houseId, "上架")
            // confirmTitle.textContent = '确认删除';
            // confirmMessage.textContent = '您确定要删除此房屋吗？删除后数据将无法恢复。';
            // confirmAction.classList.remove('btn-success');
            // confirmAction.classList.add('btn-danger');
            // confirmAction.innerHTML = '<i class="fa fa-trash"></i><span>确认删除</span>';
        });

        $(document).on("click", "#save-house", function(){
            // 这里模拟表单验证和提交
            const houseName = document.querySelector('input[name="name"]').value;

            if (!houseName) {
                showToast('error', '保存失败', '请输入房屋名称');
                return;
            }

            // 模拟API请求
            setTimeout(() => {
                let stateV=$("input[name='status']:checked").val();
                if(stateV=="active"){
                    stateV="已上架"
                }else{
                    stateV="已下架"
                }
                if(handleState=="添加") {
                    $(function () {
                        $.ajax({
                            url: baseUrl + "/admin/save",
                            type: "post",
                            headers: {
                                // 'Content-Type': "application/json;charset=UTF-8"
                                "content-type": "application/x-www-form-urlencoded"
                            },
                            data: {
                                name: $("#name").val(),
                                place: $("#city").val() + $("#address").val(),
                                price: $("#price").val(),
                                area: $("#area").val(),
                                type: $("#type").val(),
                                decorateSituation: $("#description").val(),
                                pic: imageUrl,
                                state: stateV,
                                device: getDevices()
                            },
                            success: function (res) {
                                console.log(res)
                                if (res.code == "0") {
                                    console.log("成功添加房源数据");
                                    closeHouseModal();
                                    showToast('success', '保存成功', modalTitle.textContent === '新增房屋' ? '房屋已成功添加' : '房屋信息已更新');

                                    // 重置表单
                                    document.getElementById('house-form').reset();
                                    loadInit("");
                                } else {
                                    console.log("房源数据添加失败");
                                }
                            },
                            error: function (res) {

                                console.log(res)
                            }
                        });
                        // closeHouseModal();
                        // showToast('success', '保存成功', modalTitle.textContent === '新增房屋' ? '房屋已成功添加' : '房屋信息已更新');

                        // 重置表单
                        // document.getElementById('house-form').reset();
                    }, 800);
                }else if(handleState=="编辑"){
                    $.ajax({
                        url: baseUrl + "admin/update",
                        type: "post",
                        data: {
                            id: houseId,
                            name: $("#name").val(),
                            place: $("#city").val() + $("#address").val(),
                            price: $("#price").val(),
                            area: $("#area").val(),
                            type: $("#type").val(),
                            decorateSituation: $("#description").val(),
                            pic: imageUrl,
                            state: stateV,
                            device: getDevices()
                        },
                        success: function (res) {
                            // 只有请求成功（状态码为200）才会执行这个函数
                            console.log(res);
                            if(res.code=="0"){

                                closeHouseModal();
                                showToast("success","提示","成功"+action+"商品。")

                                // 重置表单
                                document.getElementById('house-form').reset();
                                loadInit("");
                            }else{
                                showToast("warning","警告","信息更新失败，请检查错误")
                            }
                        }
                    });
                }
            });
        });
        $(document).on("click", ".下架-btn", function(){
            alert($(this).data("id")); // 可以获取data-id属性
            houseId=$(this).data("id")
            action="下架"
            openConfirmModal(houseId, "下架")
        });
        $(document).on("click", ".edit-btn", function(){
            houseId=$(this).data("id")
            modalTitle.textContent = '编辑房屋';
            houseModal.classList.remove('hidden');
            houseModal.classList.add('flex');
            document.body.style.overflow = 'hidden';
            handleState="编辑"
            $.ajax({
                url: baseUrl + "admin/info/" + houseId,
                type: "get",
                success: function (res) {
                    console.log(res)
                    if(res.code=="0"){
                        $("#name").val(res.data.name)
                        $("#price").val(res.data.price),
                        $("#area").val(res.data.area)
                        $("#type").val(res.data.type)
                        $("#description").val(res.data.decorateSituation)
                        $("#address").val(res.data.place)
                    }
                }
            });

        });
        // 如果是动态按钮
        $(document).on("click", "#confirm-action", function(){

                if(action=="delete"){
                    $.ajax({
                        url: baseUrl + "admin/delete",
                        type: "get",

                        data: {
                            ids:houseId+""
                        },
                        success: function (res) {
                            // 只有请求成功（状态码为200）才会执行这个函数
                            console.log(res);
                            if (res.code == "0") {
                                showToast("success", "提示", "成功删除商品。")
                                closeConfirmModal()
                                loadInit("");
                            } else {
                                showToast("warning", "警告", "信息更新失败，请检查错误")
                            }
                        }
                    });
                }else {
                    $.ajax({
                        url: baseUrl + "admin/updateState",
                        type: "post",

                        data: {
                            id: houseId,
                            state: "已" + action
                        },
                        success: function (res) {
                            // 只有请求成功（状态码为200）才会执行这个函数
                            console.log(res);
                            if (res.code == "0") {
                                showToast("success", "提示", "成功" + action + "商品。")
                                closeConfirmModal()
                                loadInit("");
                            } else {
                                showToast("warning", "警告", "信息更新失败，请检查错误")
                            }
                        }
                    });
                }

        });
=======
<!-- 确保在<head>中加载了jQuery -->

// 确认模态框控制
const confirmModal = document.getElementById('confirm-modal');
const cancelConfirm = document.getElementById('cancel-confirm');
const confirmAction = document.getElementById('confirm-action');
const confirmTitle = document.getElementById('confirm-title');
const confirmMessage = document.getElementById('confirm-message');

// 当前操作的房屋ID
let currentHouseId = '';
// 当前操作类型 (上架/下架)
let currentAction = '';
// 打开确认模态框
function openConfirmModal(id, action) {
    debugger
    currentHouseId = id;
    currentAction = action;

    if (action === '下架') {
        confirmTitle.textContent = '确认下架';
        confirmMessage.textContent = '您确定要将此房屋下架吗？下架后用户将无法看到该房屋。';
        confirmAction.classList.remove('btn-success');
        confirmAction.classList.add('btn-danger');
        confirmAction.innerHTML = '<i class="fa fa-ban"></i><span>确认下架</span>';
    } else if (action === '上架') {
        confirmTitle.textContent = '确认上架';
        confirmMessage.textContent = '您确定要将此房屋上架吗？上架后用户将可以看到并预订该房屋。';
        confirmAction.classList.remove('btn-danger');
        confirmAction.classList.add('btn-success');
        confirmAction.innerHTML = '<i class="fa fa-check-circle"></i><span>确认上架</span>';
    } else if (action === 'delete') {
        confirmTitle.textContent = '确认删除';
        confirmMessage.textContent = '您确定要删除此房屋吗？删除后数据将无法恢复。';
        confirmAction.classList.remove('btn-success');
        confirmAction.classList.add('btn-danger');
        confirmAction.innerHTML = '<i class="fa fa-trash"></i><span>确认删除</span>';
    }

    confirmModal.classList.remove('hidden');
    confirmModal.classList.add('flex');
    document.body.style.overflow = 'hidden';
}
// 关闭确认模态框
function closeConfirmModal() {
    confirmModal.classList.add('hidden');
    confirmModal.classList.remove('flex');
    document.body.style.overflow = '';
}

cancelConfirm.addEventListener('click', closeConfirmModal);

// 点击确认模态框外部关闭
confirmModal.addEventListener('click', (e) => {
    if (e.target === confirmModal) {
        closeConfirmModal();
    }
});

// 关闭确认模态框
function closeConfirmModal() {
    confirmModal.classList.add('hidden');
    confirmModal.classList.remove('flex');
    document.body.style.overflow = '';
}
// 通知提示框
const toast = document.getElementById('toast');
const toastIcon = document.getElementById('toast-icon');
const toastTitle = document.getElementById('toast-title');
const toastMessage = document.getElementById('toast-message');
const closeToast = document.getElementById('close-toast');

function showToast(type, title, message) {
    // 设置提示类型
    if (type === 'success') {
        toastIcon.className = 'text-success mt-0.5';
        toastIcon.innerHTML = '<i class="fa fa-check-circle text-xl"></i>';
    } else if (type === 'error') {
        toastIcon.className = 'text-danger mt-0.5';
        toastIcon.innerHTML = '<i class="fa fa-times-circle text-xl"></i>';
    } else if (type === 'warning') {
        toastIcon.className = 'text-warning mt-0.5';
        toastIcon.innerHTML = '<i class="fa fa-exclamation-triangle text-xl"></i>';
    }

    // 设置内容
    toastTitle.textContent = title;
    toastMessage.textContent = message;

    // 显示提示
    toast.classList.remove('translate-x-full');

    // 3秒后自动关闭
    setTimeout(() => {
        hideToast();
    }, 3000);
}


function hideToast() {
    toast.classList.add('translate-x-full');
}

const houseModal = document.getElementById('house-modal');
const closeModal = document.getElementById('close-modal');
const cancelModal = document.getElementById('cancel-modal');
const modalTitle = document.getElementById('modal-title');

// 关闭模态框
function closeHouseModal() {
    houseModal.classList.add('hidden');
    houseModal.classList.remove('flex');
    document.body.style.overflow = '';
}

closeModal.addEventListener('click', closeHouseModal);
cancelModal.addEventListener('click', closeHouseModal);
function getHouseDataById(id) {
    $.ajax({
        url: baseUrl + "/admin/info/"+id,
        type: "get",

        success: function (res) {
            console.log(res)
            if (res.code == "0") {
                viewHouseDetail(res.data)
            } else {
                console.log("没有成功查询房源");
            }
        },
        error: function (res) {

            console.log(res)
        }
    });
}

// 查看房屋详情
function viewHouseDetail(houseData) {

    if (houseData) {
        let imgUrl=baseUrl+houseData.pic;
        // 创建详情模态框内容
        const detailContent = `
      <div class="p-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <img src="${imgUrl}" alt="${houseData.name}" class="w-full h-64 object-cover rounded-lg">
          </div>
          <div>
            <h3 class="text-xl font-bold mb-2">${houseData.name}</h3>
            <p class="text-gray-600 mb-4">${houseData.place}</p>
            <div class="grid grid-cols-2 gap-4 mb-4">
              <div>
                <p class="text-sm text-gray-500">租金</p>
                <p class="font-medium">${houseData.price}元/月</p>
              </div>
              <div>
                <p class="text-sm text-gray-500">面积</p>
                <p class="font-medium">${houseData.area}㎡</p>
              </div>
              <div>
                <p class="text-sm text-gray-500">户型</p>
                <p class="font-medium">${houseData.type}</p>
              </div>
              <div>
                <p class="text-sm text-gray-500">状态</p>
                <p class="font-medium">${houseData.state}</p>
              </div>
            </div>
            <div class="mb-4">
              <p class="text-sm text-gray-500 mb-1">房屋描述</p>
              <p class="text-gray-700">${houseData.decorateSituation}</p>
            </div>
          </div>
        </div>
      </div>
    `;

        // 创建并显示详情模态框
        const detailModal = document.createElement('div');
        detailModal.id = 'detail-modal';
        detailModal.className = 'fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4';
        detailModal.innerHTML = `
      <div class="card w-full max-w-4xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-bold">房屋详情</h3>
          <button class="close-detail-modal text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        ${detailContent}
        <div class="p-6 border-t border-gray-200 flex items-center justify-end">
          <button class="close-detail-modal btn btn-primary">关闭</button>
        </div>
      </div>
    `;

        document.body.appendChild(detailModal);
        document.body.style.overflow = 'hidden';

        // 关闭详情模态框事件
        detailModal.querySelectorAll('.close-detail-modal').forEach(btn => {
            btn.addEventListener('click', () => {
                detailModal.remove();
                document.body.style.overflow = '';
            });
        });
    }
}

    $(document).ready(function(){
        let houseId="";
        let action="";
        $(document).on("click", "#add-house-btn", function(){
            modalTitle.textContent = '新增房屋';
            houseModal.classList.remove('hidden');
            houseModal.classList.add('flex');
            document.body.style.overflow = 'hidden';
            handleState="添加"
        });

        $(document).on("click", ".detail-btn", function(){
            getHouseDataById($(this).data("id"))
        });
        $(document).on("click", ".delete-btn", function(){
            action="delete";
            openConfirmModal($(this).data("id"), 'delete');
        });
        const imageUpload = document.getElementById('image-upload');
        const imagePreview = document.getElementById('image-preview');
        $(document).on("change", "#image-upload", function(e){
            debugger
            if (e.target.files.length > 0) {
                imagePreview.classList.remove('hidden');
                // 实际项目中应该根据上传的文件显示预览
                // 这里只是简单显示示例图片
                // 获取文件输入元素
                // const fileInput = $(imageUpload); // 假设你的文件输入框id为fileInput

// 创建FormData对象并添加文件
                const formData = new FormData();
                formData.append('file', imageUpload.files[0]); // 'file'为后端接收的参数名
                //formData.append('extraParam', 'value'); // 可添加其他参数

                $.ajax({
                    url: baseUrl + "file/upload",
                    type: "POST",
                    data: formData,

                    // 必须配置项
                    contentType: false, // 必须false才会自动带上正确的Content-Type
                    processData: false, // 必须false才会避免jQuery将FormData转为字符串

                    // 可选：上传进度提示
                    xhr: function() {
                        const xhr = new XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                const percent = Math.round((e.loaded / e.total) * 100);
                                console.log('上传进度:', percent + '%');
                                // 可在此处更新进度条UI
                            }
                        }, false);
                        return xhr;
                    },

                    success: function(res) {
                        console.log(res)
                        if (res.code == "0") {
                            console.log('上传成功:', res);
                            imageUrl=res.file;
                            // 处理成功逻辑，例如显示预览图
                            $('#backImg').attr('src',baseUrl+ res.file+"?time="+new Date().getTime());
                        } else {
                            console.error('上传失败:');
                            // alert('上传失败: ' + res.message);
                        }
                    },

                    error: function(xhr, status, error) {
                        console.error('请求异常:', status, error);
                        alert('上传请求失败，请检查网络连接');
                    }
                });
            }
        });
        // 如果是动态按钮
        $(document).on("click", ".上架-btn", function(){
            // alert($(this).data("id")); // 可以获取data-id属性
            houseId=$(this).data("id")
            action="上架"
            openConfirmModal(houseId, "上架")
        });
        $(document).on("click", ".delete-btn", function(){
            houseId=$(this).data("id")
            action="delete"
            openConfirmModal(houseId, "上架")
            // confirmTitle.textContent = '确认删除';
            // confirmMessage.textContent = '您确定要删除此房屋吗？删除后数据将无法恢复。';
            // confirmAction.classList.remove('btn-success');
            // confirmAction.classList.add('btn-danger');
            // confirmAction.innerHTML = '<i class="fa fa-trash"></i><span>确认删除</span>';
        });

        $(document).on("click", "#save-house", function(){
            // 这里模拟表单验证和提交
            const houseName = document.querySelector('input[name="name"]').value;

            if (!houseName) {
                showToast('error', '保存失败', '请输入房屋名称');
                return;
            }

            // 模拟API请求
            setTimeout(() => {
                let stateV=$("input[name='status']:checked").val();
                if(stateV=="active"){
                    stateV="已上架"
                }else{
                    stateV="已下架"
                }
                if(handleState=="添加") {
                    $(function () {
                        $.ajax({
                            url: baseUrl + "/admin/save",
                            type: "post",
                            headers: {
                                // 'Content-Type': "application/json;charset=UTF-8"
                                "content-type": "application/x-www-form-urlencoded"
                            },
                            data: {
                                name: $("#name").val(),
                                place: $("#city").val() + $("#address").val(),
                                price: $("#price").val(),
                                area: $("#area").val(),
                                type: $("#type").val(),
                                decorateSituation: $("#description").val(),
                                pic: imageUrl,
                                state: stateV,
                                device: getDevices()
                            },
                            success: function (res) {
                                console.log(res)
                                if (res.code == "0") {
                                    console.log("成功添加房源数据");
                                    closeHouseModal();
                                    showToast('success', '保存成功', modalTitle.textContent === '新增房屋' ? '房屋已成功添加' : '房屋信息已更新');

                                    // 重置表单
                                    document.getElementById('house-form').reset();
                                    loadInit("");
                                } else {
                                    console.log("房源数据添加失败");
                                }
                            },
                            error: function (res) {

                                console.log(res)
                            }
                        });
                        // closeHouseModal();
                        // showToast('success', '保存成功', modalTitle.textContent === '新增房屋' ? '房屋已成功添加' : '房屋信息已更新');

                        // 重置表单
                        // document.getElementById('house-form').reset();
                    }, 800);
                }else if(handleState=="编辑"){
                    $.ajax({
                        url: baseUrl + "admin/update",
                        type: "post",
                        data: {
                            id: houseId,
                            name: $("#name").val(),
                            place: $("#city").val() + $("#address").val(),
                            price: $("#price").val(),
                            area: $("#area").val(),
                            type: $("#type").val(),
                            decorateSituation: $("#description").val(),
                            pic: imageUrl,
                            state: stateV,
                            device: getDevices()
                        },
                        success: function (res) {
                            // 只有请求成功（状态码为200）才会执行这个函数
                            console.log(res);
                            if(res.code=="0"){

                                closeHouseModal();
                                showToast("success","提示","成功"+action+"商品。")

                                // 重置表单
                                document.getElementById('house-form').reset();
                                loadInit("");
                            }else{
                                showToast("warning","警告","信息更新失败，请检查错误")
                            }
                        }
                    });
                }
            });
        });
        $(document).on("click", ".下架-btn", function(){
            alert($(this).data("id")); // 可以获取data-id属性
            houseId=$(this).data("id")
            action="下架"
            openConfirmModal(houseId, "下架")
        });
        $(document).on("click", ".edit-btn", function(){
            houseId=$(this).data("id")
            modalTitle.textContent = '编辑房屋';
            houseModal.classList.remove('hidden');
            houseModal.classList.add('flex');
            document.body.style.overflow = 'hidden';
            handleState="编辑"
            $.ajax({
                url: baseUrl + "admin/info/" + houseId,
                type: "get",
                success: function (res) {
                    console.log(res)
                    if(res.code=="0"){
                        $("#name").val(res.data.name)
                        $("#price").val(res.data.price),
                        $("#area").val(res.data.area)
                        $("#type").val(res.data.type)
                        $("#description").val(res.data.decorateSituation)
                        $("#address").val(res.data.place)
                    }
                }
            });

        });
        // 如果是动态按钮
        $(document).on("click", "#confirm-action", function(){

                if(action=="delete"){
                    $.ajax({
                        url: baseUrl + "admin/delete",
                        type: "get",

                        data: {
                            ids:houseId+""
                        },
                        success: function (res) {
                            // 只有请求成功（状态码为200）才会执行这个函数
                            console.log(res);
                            if (res.code == "0") {
                                showToast("success", "提示", "成功删除商品。")
                                closeConfirmModal()
                                loadInit("");
                            } else {
                                showToast("warning", "警告", "信息更新失败，请检查错误")
                            }
                        }
                    });
                }else {
                    $.ajax({
                        url: baseUrl + "admin/updateState",
                        type: "post",

                        data: {
                            id: houseId,
                            state: "已" + action
                        },
                        success: function (res) {
                            // 只有请求成功（状态码为200）才会执行这个函数
                            console.log(res);
                            if (res.code == "0") {
                                showToast("success", "提示", "成功" + action + "商品。")
                                closeConfirmModal()
                                loadInit("");
                            } else {
                                showToast("warning", "警告", "信息更新失败，请检查错误")
                            }
                        }
                    });
                }

        });
>>>>>>> 66dcee4e153c16ef05fd0c7e1ed9f414a0bf0bc9
    });